package com.tiennt.android.callnotes.fragments;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.Fragment;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.tiennt.android.callnotes.AddNoteActivity;
import com.tiennt.android.callnotes.R;
import com.tiennt.android.callnotes.models.contentholders.CallLogItem;
import com.tiennt.android.callnotes.models.listadapters.CallLogAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

public class CallLogFragment extends Fragment {
	private final String TAG = "CallLogFragment";
	private final boolean DBG = true;
	public static final int REQUEST_ADD_CONTACT = 1003;

	private ListView mListCall;
	private CallLogAdapter mCallLogAdapter;
	private ArrayList<CallLogItem> mCallLogsData;
	private int mCallType;
	ProgressBar mProgressBar;
	private final int GET_DATA_COMPLETE = 1;

	@Override
	public void onActivityCreated(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onActivityCreated(arg0);
		log("" + (getActivity() == null));
		new GetCallLogAsyncTask().execute();
		// setupListView();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View root = inflater.inflate(R.layout.frag_calllog, container, false);
		Bundle args = getArguments();
		mCallType = args.getInt(ProjectUtils.BUNDLEKEY_CALLTYPE);

		mListCall = (ListView) root.findViewById(R.id.lvCallLog);
		mProgressBar = (ProgressBar) root.findViewById(R.id.progrees);

		return root;
	}

	public class GetCallLogAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			msgHandler.sendEmptyMessage(GET_DATA_COMPLETE);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mCallLogsData = getCallLogs();
			return null;
		}

	}

	public AdapterView.OnItemClickListener onListItemClick = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			final CallLogItem item = mCallLogAdapter.getItem(position);
			log("" + (item == null));
			if (item.getContactName() == null
					|| item.getContactName().equals("")) {
				AlertDialog.Builder alert = new AlertDialog.Builder(
						getActivity());
				alert.setTitle("");
				alert.setMessage("Add to contacts?");

				alert.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent i = new Intent(
										Intent.ACTION_INSERT_OR_EDIT);
								i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
								i.putExtra(Insert.PHONE, item.getNumber());
								startActivityForResult(i, REQUEST_ADD_CONTACT);
							}
						});

				alert.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						});
				alert.create().show();
			} else {
				// Show context menu.
				// parent.showContextMenu();
				final int start = parent.getFirstVisiblePosition();
				final int index = position - start;
				final View childView = parent.getChildAt(index);
				if (childView != null) {
					parent.showContextMenuForChild(childView);
				}
			}
		}

	};

	public OnCreateContextMenuListener onListViewCtxCreate = new OnCreateContextMenuListener() {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			// TODO Auto-generated method stub
			menu.setHeaderTitle("Option");
			MenuInflater inflater = getActivity().getMenuInflater();
			inflater.inflate(R.menu.calllogs, menu);
		}
	};

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		log("Position: " + info.position);
		final CallLogItem calllogItem = mCallLogAdapter.getItem(info.position);

		switch (item.getItemId()) {
		case R.id.action_addnote:
			Intent intent2 = new Intent(getActivity(), AddNoteActivity.class);
			Bundle data = new Bundle();
			data.putString(ProjectUtils.BUNDLEKEY_CONTACTID,
					calllogItem.getContactId());
			data.putString(ProjectUtils.BUNDLEKEY_CONTACTNAME,
					calllogItem.getContactName());
			intent2.putExtras(data);
			startActivity(intent2);
			break;
		case R.id.action_call:
			String uriString = "tel:" + calllogItem.getNumber().trim();
			Intent intent = new Intent(Intent.ACTION_CALL);
			intent.setData(Uri.parse(uriString));
			startActivity(intent);
			break;
		case R.id.action_sms:
			uriString = "smsto:" + calllogItem.getNumber().trim();
			Uri uri = Uri.parse(uriString);
			Intent it = new Intent(Intent.ACTION_SENDTO, uri);
			startActivity(it);
			break;
		default:
			return super.onContextItemSelected(item);

		}
		return true;
	}

	public ArrayList<CallLogItem> getCallLogs() {
		ArrayList<CallLogItem> results = new ArrayList<CallLogItem>();

		String selection = null;
		if (mCallType == ProjectUtils.CALLTYPE_INCOMING) {
			selection = CallLog.Calls.TYPE + " = "
					+ CallLog.Calls.INCOMING_TYPE;
		} else if (mCallType == ProjectUtils.CALLTYPE_MISSED) {
			selection = CallLog.Calls.TYPE + " = " + CallLog.Calls.MISSED_TYPE;
		} else if (mCallType == ProjectUtils.CALLTYPE_OUTGOING) {
			selection = CallLog.Calls.TYPE + " = "
					+ CallLog.Calls.OUTGOING_TYPE;
		}

		Cursor cursor = getActivity().getContentResolver().query(
				CallLog.Calls.CONTENT_URI, null, selection, null,
				CallLog.Calls.DATE + " desc");

		int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
		int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
		int date = cursor.getColumnIndex(CallLog.Calls.DATE);
		int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);

		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,
				DateFormat.DEFAULT, Locale.US);

		while (cursor.moveToNext()) {

			String strname = "";
			String contactId = "";
			String phNumber = cursor.getString(number);

			Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
					Uri.encode(phNumber));

			Cursor c = getActivity().getContentResolver().query(uri,
					new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
					null, null, null);
			if (c.moveToFirst()) {
				strname = c.getString(c
						.getColumnIndex(PhoneLookup.DISPLAY_NAME));
				contactId = c.getInt(c.getColumnIndex(PhoneLookup._ID)) + "";
			}

			c.close();
			String callType = cursor.getString(type);
			String callDate = cursor.getString(date);
			String callDuration = cursor.getString(duration);

			String formatedTime = (String) df.format(new Date(Long
					.parseLong(callDate)));

			// String formatedTime = dateFormater.format(new Date(Long
			// .parseLong(callDate)));"MMMM dd, yyyy h:mm:ss AA"
			long durationInMili = Long.parseLong(callDuration);
			String formatedDuration = "" + durationInMili / 60 + " min "
					+ durationInMili % 60 + " sec";

			CallLogItem item = new CallLogItem();
			item.setContactId(contactId);
			item.setCallType(Integer.parseInt(callType));
			item.setContactName(strname);
			item.setTime(formatedTime);
			item.setLong(formatedDuration);
			item.setNumber(PhoneNumberUtils.formatNumber(phNumber));

			results.add(item);
		}
		cursor.close();

		return results;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQUEST_ADD_CONTACT) {
			if (resultCode == Activity.RESULT_OK) {
				new GetCallLogAsyncTask().execute();
			}
		}
	}

	private Handler msgHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == GET_DATA_COMPLETE) {
				mProgressBar.setVisibility(View.GONE);
				mListCall.setVisibility(View.VISIBLE);
				mCallLogAdapter = new CallLogAdapter(getActivity(),
						R.layout.list_contacts_row, mCallLogsData);
				mListCall.setAdapter(mCallLogAdapter);
				mListCall.setOnItemClickListener(onListItemClick);
				mListCall.setOnCreateContextMenuListener(onListViewCtxCreate);
			}
			return true;
		}
	});

	public void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}
}
